package com.chen.designmode;

/**
 * 第一种（懒汉，线程不安全）：这种写法lazy loading很明显，但是致命的是在多线程不能正常工作。
 * @author Administrator
 *
 */
public class SingtonTest {

	private SingtonTest(){};
	private static SingtonTest singtonTest;
	
	public static SingtonTest getInstance(){
		if(singtonTest ==null){
			singtonTest = new SingtonTest();
		}
		return singtonTest;
	}
}

/**
 * 第一种（懒汉，线程安全）：
 * @author Administrator
 *
 */
class SingtonTest1 {
	
	private SingtonTest1(){};
	private static SingtonTest1 singtonTest;
	
	public static synchronized SingtonTest1 getInstance(){
		if(singtonTest ==null){
			singtonTest = new SingtonTest1();
		}
		return singtonTest;
	}
}

/**
 * 第三种（饿汉）：
 * @author Administrator
 *
 */
class SingtonTest2 {
	private SingtonTest2(){}
	private static SingtonTest2 singtonTest2 = new SingtonTest2();
	public static SingtonTest2 getInstance(){
		return singtonTest2;
	}
}
/**
 * 第四种（饿汉）：
 * @author Administrator
 *
 */
class SingtonTest3 {
	private SingtonTest3(){}
	private static SingtonTest3 singtonTest3 = null;
	static{
		singtonTest3 = new SingtonTest3();
	}
	public static SingtonTest3 getInstance(){
		return singtonTest3;
	}
}

/**
 * 第五种（静态内部类）：
 * @author Administrator
 *
 */
class SingtonTest4{
	private SingtonTest4(){}
	public static class SingtonHold{
		private static final SingtonTest4 singtonTest4 = new SingtonTest4();
	}
	public static SingtonTest4 getInstance(){
		return SingtonHold.singtonTest4;
	}
}

/**
 * 第七种（双重校验锁）：
 * @author Administrator
 *
 */
class SingtonTest5{
	private SingtonTest5(){}
	private volatile static SingtonTest5 singtonTest5;
	public static SingtonTest5 getInstance(){
		if(singtonTest5==null){
			synchronized(SingtonTest5.class){
				if(singtonTest5==null){
					singtonTest5 = new SingtonTest5();
				}
			}
		}
		return singtonTest5;
	}
}
